<?php
/**
 * 蜘蛛监控插件 - 许可证管理函数库（更新版）
 * 支持一次性授权100年和全功能模式
 * 作者：Eric
 * 网站：https://zibovip.top
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * 生成许可证密钥
 */
function spider_generate_license_key($length = 25) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $license_key = '';
    
    for ($i = 0; $i < $length; $i++) {
        $license_key .= $characters[rand(0, strlen($characters) - 1)];
        if (($i + 1) % 5 == 0 && $i < $length - 1) {
            $license_key .= '-';
        }
    }
    
    return $license_key;
}

/**
 * 验证许可证密钥格式
 */
function spider_validate_license_key($license_key) {
    return preg_match('/^[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}$/', $license_key);
}

/**
 * 获取功能列表
 */
function spider_get_feature_list() {
    return [
        'basic_stats' => '基础统计',
        'daily_report' => '每日报告',
        'spider_tracking' => '蜘蛛追踪',
        'advanced_stats' => '高级统计',
        'export_data' => '导出数据',
        'clear_data' => '清理数据',
        'real_time_update' => '实时更新',
        'api_access' => 'API访问',
        'multi_site' => '多站点支持',
        'priority_support' => '优先支持'
    ];
}

/**
 * 获取所有功能
 */
function spider_get_all_features() {
    return array_keys(spider_get_feature_list());
}

/**
 * 获取套餐配置（保留兼容，但默认使用全功能）
 */
function spider_get_plan_config($plan = null) {
    $all_features = spider_get_all_features();
    
    $plans = [
        'basic' => [
            'name' => '永久授权版',
            'price' => 999,
            'max_domains' => 999,
            'features' => $all_features
        ],
        'pro' => [
            'name' => '永久授权版',
            'price' => 999,
            'max_domains' => 999,
            'features' => $all_features
        ],
        'enterprise' => [
            'name' => '永久授权版',
            'price' => 999,
            'max_domains' => 999,
            'features' => $all_features
        ]
    ];
    
    return $plan ? ($plans[$plan] ?? $plans['basic']) : $plans;
}

/**
 * 检查许可证是否有效
 */
function spider_is_license_valid($license_key, $domain) {
    $service = new Spider_License_Service();
    $result = $service->verify_license($license_key, $domain);
    return $result['success'] ?? false;
}

/**
 * 获取许可证信息
 */
function spider_get_license_info($license_key, $domain) {
    $service = new Spider_License_Service();
    return $service->get_license_details($license_key, $domain);
}

/**
 * 添加许可证（更新版）
 */
function spider_add_license($data) {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    
    // 生成许可证密钥
    $license_key = !empty($data['license_key']) ? $data['license_key'] : spider_generate_license_key();
    
    if (!spider_validate_license_key($license_key)) {
        return new WP_Error('invalid_key', '许可证密钥格式无效');
    }
    
    // 检查密钥是否已存在
    $exists = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$licenses_table} WHERE license_key = %s",
        $license_key
    ));
    
    if ($exists) {
        return new WP_Error('duplicate_key', '许可证密钥已存在');
    }
    
    // 设置默认值为100年授权和全功能
    $expires_at = date('Y-m-d', strtotime('+100 years'));
    $all_features = spider_get_all_features();
    $max_domains = isset($data['max_domains']) ? intval($data['max_domains']) : 999;
    
    $result = $wpdb->insert(
        $licenses_table,
        [
            'license_key' => $license_key,
            'plan' => 'basic', // 统一使用basic类型
            'features' => json_encode($all_features),
            'max_domains' => $max_domains,
            'expires_at' => $expires_at,
            'created_at' => current_time('mysql')
        ],
        ['%s', '%s', '%s', '%d', '%s', '%s']
    );
    
    if ($result) {
        return $license_key;
    }
    
    return new WP_Error('insert_failed', '添加许可证失败');
}

/**
 * 生成单个激活码（限制为一次一个，优先存入数据表）
 */
function spider_generate_single_license($plan = 'basic', $expires_at = null) {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    
    // 使用100年授权和全功能
    if (!$expires_at) {
        $expires_at = date('Y-m-d', strtotime('+100 years'));
    }
    
    $all_features = spider_get_all_features();
    $max_domains = 999; // 默认最大域名数
    
    // 生成唯一激活码
    $license_key = spider_generate_license_key();
    
    // 检查激活码是否已存在
    $exists = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$licenses_table} WHERE license_key = %s",
        $license_key
    ));
    
    if ($exists > 0) {
        // 如果激活码已存在，重新生成
        return spider_generate_single_license($plan, $expires_at);
    }
    
    // 直接存入数据表
    $result = $wpdb->insert(
        $licenses_table,
        [
            'license_key' => $license_key,
            'plan' => $plan,
            'features' => json_encode($all_features),
            'max_domains' => $max_domains,
            'expires_at' => $expires_at,
            'created_at' => current_time('mysql')
        ],
        ['%s', '%s', '%s', '%d', '%s', '%s']
    );
    
    if ($result) {
        return [
            'success' => true,
            'license_key' => $license_key,
            'expires_at' => $expires_at,
            'message' => '激活码生成成功并已存入数据表'
        ];
    } else {
        return [
            'success' => false,
            'message' => '激活码存入数据表失败'
        ];
    }
}

/**
 * 批量生成许可证（已废弃，改为单个生成）
 * @deprecated 使用 spider_generate_single_license 代替
 */
function spider_batch_generate_licenses($count, $plan = 'basic', $expires_at = null) {
    // 强制限制为1个
    return [spider_generate_single_license($plan, $expires_at)];
}

/**
 * 获取所有许可证
 */
function spider_get_all_licenses($limit = 100, $offset = 0) {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    
    $licenses = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT l.*, COUNT(a.id) as activation_count 
             FROM {$licenses_table} l 
             LEFT JOIN {$activations_table} a ON l.id = a.license_id 
             GROUP BY l.id 
             ORDER BY l.created_at DESC 
             LIMIT %d OFFSET %d",
            $limit,
            $offset
        ),
        ARRAY_A
    );
    
    // 解码功能列表
    foreach ($licenses as &$license) {
        $license['features'] = json_decode($license['features'], true);
        $license['expires_in'] = human_time_diff(strtotime($license['expires_at']), current_time('timestamp'));
        $license['is_expired'] = strtotime($license['expires_at']) < current_time('timestamp');
    }
    
    return $licenses;
}

/**
 * 删除许可证
 */
function spider_delete_license($license_id) {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    
    return $wpdb->delete(
        $licenses_table,
        ['id' => intval($license_id)],
        ['%d']
    );
}

/**
 * 清理过期许可证（保留30天）
 */
function spider_cleanup_expired_licenses() {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    
    $result = $wpdb->query(
        "DELETE FROM {$licenses_table} WHERE expires_at < DATE_SUB(NOW(), INTERVAL 30 DAY)"
    );
    
    return (int) $result;
}

/**
 * 获取许可证状态
 */
function spider_get_license_status($license) {
    if (!is_array($license)) {
        return 'unknown';
    }
    
    $expires_at = strtotime($license['expires_at']);
    $now = current_time('timestamp');
    
    if ($expires_at < $now) {
        return 'expired';
    }
    
    return 'active';
}

/**
 * 获取状态文本
 */
function spider_get_status_text($status) {
    switch ($status) {
        case 'active':
            return '<span style="color: green;">✓ 有效</span>';
        case 'expired':
            return '<span style="color: red;">✗ 已过期</span>';
        default:
            return '<span style="color: gray;">？ 未知</span>';
    }
}

/**
 * 激活许可证
 */
function spider_activate_license($license_key, $domain, $ip_address = '', $user_agent = '', $access_token = '', $token_expires_at = '', $token_meta = '') {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    
    // 验证许可证密钥格式
    if (!spider_validate_license_key($license_key)) {
        return new WP_Error('invalid_key', '许可证密钥格式无效');
    }
    
    // 查找许可证
    $license = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$licenses_table} WHERE license_key = %s",
        $license_key
    ));
    
    if (!$license) {
        return [
            'success' => false,
            'message' => '许可证不存在或无效'
        ];
    }
    
    // 检查是否过期
    if (strtotime($license->expires_at) < current_time('timestamp')) {
        return [
            'success' => false,
            'message' => '许可证已过期'
        ];
    }
    
    // 检查激活数量限制
    $current_activations = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$activations_table} WHERE license_id = %d",
        $license->id
    ));
    
    if ($current_activations >= $license->max_domains) {
        return [
            'success' => false,
            'message' => '许可证已达到最大激活数量限制'
        ];
    }
    
    // 规范化：仅保存域名 host，避免协议/路径差异
    $domain_host = wp_parse_url($domain, PHP_URL_HOST);
    if (empty($domain_host)) {
        // 兜底：去除协议和路径，仅保留主机名
        $domain_host = preg_replace('#^https?://#i', '', (string) $domain);
        $domain_host = preg_replace('#/.*$#', '', $domain_host);
    }
    $domain_host = strtolower(trim($domain_host));
    // 只保留本次激活：删除该许可证在其他域名上的所有历史激活记录
    $wpdb->query($wpdb->prepare(
        "DELETE FROM {$activations_table} WHERE license_id = %d AND domain <> %s",
        $license->id,
        $domain_host
    ));

    // 检查是否已经在此域名存在记录（删除后通常为0，兼容重复请求场景）
    $existing = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$activations_table} WHERE license_id = %d AND domain = %s",
        $license->id,
        $domain_host
    ));
    
    if ($existing > 0) {
        // 已在该域名激活：为现有记录签发并回填最新令牌（生产RS256）
        $has_token_col = $wpdb->get_var("SHOW COLUMNS FROM {$activations_table} LIKE 'access_token'");
        if (!empty($has_token_col)) {
            if (!function_exists('generate_access_token')) {
                $sec_file = dirname(__FILE__) . '/secure-license-verification.php';
                if (file_exists($sec_file)) { require_once $sec_file; }
            }
            $ttl = defined('DAY_IN_SECONDS') ? (7 * DAY_IN_SECONDS) : (7 * 24 * 3600);
            $issued = function_exists('generate_access_token') ? generate_access_token($license_key, $domain_host, 'general', 'general', $ttl) : false;
            if (is_array($issued) && !empty($issued['token'])) {
                $wpdb->update(
                    $activations_table,
                    [
                        'access_token' => $issued['token'],
                        'token_issued_at' => current_time('mysql'),
                        'token_expires_at' => date('Y-m-d H:i:s', time() + $ttl),
                        'token_status' => 'active'
                    ],
                    [ 'license_id' => $license->id, 'domain' => $domain_host ],
                    [ '%s', '%s', '%s', '%s' ],
                    [ '%d', '%s' ]
                );
            }
        }
        return [
            'success' => true,
            'message' => '许可证已在此域名激活',
            'license_key' => $license_key,
            'plan' => $license->plan,
            'expires_at' => $license->expires_at,
            'features' => json_decode($license->features, true),
            'max_domains' => (int) $license->max_domains,
            'current_activations' => 1
        ];
    }
    
    // 记录激活（仅保存域名 host），并写入 license_key 与 token 信息
    $insert_data = [
        'license_id' => $license->id,
        'license_key' => $license_key,
        'domain' => $domain_host,
        'status' => 'active',
        'activated_at' => current_time('mysql')
    ];
    // 服务端签发令牌并落库（若表已增加相关字段）- 使用 RS256，与生产模式一致
    $has_token_col = $wpdb->get_var("SHOW COLUMNS FROM {$activations_table} LIKE 'access_token'");
    if (!empty($has_token_col)) {
        // 确保签发函数可用
        if (!function_exists('generate_access_token')) {
            $sec_file = dirname(__FILE__) . '/secure-license-verification.php';
            if (file_exists($sec_file)) { require_once $sec_file; }
        }
        $ttl = defined('DAY_IN_SECONDS') ? (7 * DAY_IN_SECONDS) : (7 * 24 * 3600);
        $issued = function_exists('generate_access_token') ? generate_access_token($license_key, $domain_host, 'general', 'general', $ttl) : false;
        if (is_array($issued) && !empty($issued['token'])) {
            $insert_data['access_token'] = $issued['token'];
            $insert_data['token_issued_at'] = current_time('mysql');
            $insert_data['token_expires_at'] = date('Y-m-d H:i:s', time() + $ttl);
            $insert_data['token_status'] = 'active';
            if (!empty($token_meta)) { $insert_data['token_meta'] = $token_meta; }
        } else {
            // 生产模式：没有生成 RS256 令牌则视为失败，避免出现“已激活但无令牌”的不一致状态
            if (defined('WP_DEBUG') && WP_DEBUG) {
                @error_log('[SpiderLicense] Activation aborted: RS256 token not issued (check server private key)');
            }
            return [
                'success' => false,
                'message' => '服务端未签发访问令牌，请配置RSA私钥后重试激活'
            ];
        }
    }
    $result = $wpdb->insert($activations_table, $insert_data);
    
    if ($result) {
        return [
            'success' => true,
            'message' => '许可证激活成功',
            'license_key' => $license_key,
            'plan' => $license->plan,
            'expires_at' => $license->expires_at,
            'features' => json_decode($license->features, true),
            'max_domains' => (int) $license->max_domains,
            'current_activations' => $current_activations + 1
        ];
    }
    
    return [
        'success' => false,
        'message' => '激活失败，请重试'
    ];
}

/**
 * 验证许可证状态
 */
function spider_verify_license($license_key, $domain) {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    
    // 验证许可证密钥格式
    if (!spider_validate_license_key($license_key)) {
        return new WP_Error('invalid_key', '许可证密钥格式无效');
    }
    
    // 查找许可证
    $license = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$licenses_table} WHERE license_key = %s",
        $license_key
    ));
    
    if (!$license) {
        return [
            'success' => false,
            'message' => '许可证不存在或无效',
            'status' => 'invalid'
        ];
    }
    
    // 检查是否过期
    $is_expired = strtotime($license->expires_at) < current_time('timestamp');
    
    // 规范化域名：仅保存域名 host，避免协议/路径差异
    $domain_host = wp_parse_url($domain, PHP_URL_HOST);
    if (empty($domain_host)) {
        // 兜底：去除协议和路径，仅保留主机名
        $domain_host = preg_replace('#^https?://#i', '', (string) $domain);
        $domain_host = preg_replace('#/.*$#', '', $domain_host);
    }
    $domain_host = strtolower(trim($domain_host));
    
    // 检查是否在此域名激活
    $is_activated = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$activations_table} WHERE license_id = %d AND domain = %s AND status = 'active'",
        $license->id,
        $domain_host
    )) > 0;
    
    // 返回激活记录详情
    $activation = $wpdb->get_row($wpdb->prepare(
        "SELECT id, license_id, domain, status, activated_at, last_check, ip_address, user_agent FROM {$activations_table} WHERE license_id = %d AND domain = %s",
        $license->id,
        $domain_host
    ), ARRAY_A);

    return [
        'success' => true,
        'status' => $is_expired ? 'expired' : ($is_activated ? 'active' : 'inactive'),
        'license_key' => $license_key,
        'plan' => $license->plan,
        'expires_at' => $license->expires_at,
        'features' => json_decode($license->features, true),
        'max_domains' => (int) $license->max_domains,
        'is_activated' => $is_activated,
        'is_expired' => $is_expired,
        'activation' => $activation
    ];
}

/**
 * 获取某域名激活状态（辅助接口）
 */
function spider_get_activation_status($domain, $license_key = null) {
    global $wpdb;
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    $licenses_table = $wpdb->prefix . 'spider_licenses';

    // 规范化域名：仅保存域名 host，避免协议/路径差异
    $domain_host = wp_parse_url($domain, PHP_URL_HOST);
    if (empty($domain_host)) {
        // 兜底：去除协议和路径，仅保留主机名
        $domain_host = preg_replace('#^https?://#i', '', (string) $domain);
        $domain_host = preg_replace('#/.*$#', '', $domain_host);
    }
    $domain_host = strtolower(trim($domain_host));

    if ($license_key) {
        $license_id = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$licenses_table} WHERE license_key=%s", $license_key));
        if (!$license_id) return ['success' => true, 'data' => null];
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT id, license_id, domain, status, activated_at, last_check, ip_address, user_agent FROM {$activations_table} WHERE license_id=%d AND domain=%s",
            $license_id, $domain_host
        ), ARRAY_A);
    } else {
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT id, license_id, domain, status, activated_at, last_check, ip_address, user_agent FROM {$activations_table} WHERE domain=%s ORDER BY id DESC LIMIT 1",
            $domain_host
        ), ARRAY_A);
    }
    return ['success' => true, 'data' => $row];
}

/**
 * 停用许可证
 */
function spider_deactivate_license($license_key, $domain) {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    
    // 验证许可证密钥格式
    if (!spider_validate_license_key($license_key)) {
        return new WP_Error('invalid_key', '许可证密钥格式无效');
    }
    
    // 查找许可证
    $license = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$licenses_table} WHERE license_key = %s",
        $license_key
    ));
    
    // 规范化域名：仅保存域名 host，避免协议/路径差异
    $domain_host = wp_parse_url($domain, PHP_URL_HOST);
    if (empty($domain_host)) {
        // 兜底：去除协议和路径，仅保留主机名
        $domain_host = preg_replace('#^https?://#i', '', (string) $domain);
        $domain_host = preg_replace('#/.*$#', '', $domain_host);
    }
    $domain_host = strtolower(trim($domain_host));

    if (!$license) {
        // 宽松处理：即使许可证记录不存在，也按域名尝试停用；无记录亦视为已停用
        $wpdb->update($activations_table, ['status' => 'inactive'], ['domain' => $domain_host], ['%s'], ['%s']);
        $wpdb->delete($activations_table, [ 'domain' => $domain_host ], [ '%s' ]);
        return [
            'success' => true,
            'message' => '许可证已停用（按域名处理）',
            'fallback' => true
        ];
    }
    
    // 删除此域名的激活记录
    $result = $wpdb->delete(
        $activations_table,
        [
            'license_id' => $license->id,
            'domain' => $domain_host
        ],
        ['%d', '%s']
    );
    
    if ($result) {
        // 也可以不删除而是更新状态
        $wpdb->update($activations_table, ['status' => 'inactive'], ['license_id' => $license->id, 'domain' => $domain_host], ['%s'], ['%d', '%s']);
        return [
            'success' => true,
            'message' => '许可证已停用'
        ];
    }
    
    return [
        'success' => false,
        'message' => '许可证未在此域名激活'
    ];
}

/**
 * 检查功能权限
 */
function spider_check_feature_access($license_key, $domain, $feature) {
    $verify_result = spider_verify_license($license_key, $domain);
    
    if (!$verify_result['success']) {
        return $verify_result;
    }
    
    if ($verify_result['status'] !== 'active') {
        return [
            'success' => false,
            'message' => '许可证未激活或已过期',
            'has_access' => false
        ];
    }
    
    // 检查功能权限
    $features = $verify_result['features'] ?? [];
    $has_access = in_array($feature, $features) || in_array('all', $features);
    
    return [
        'success' => true,
        'has_access' => $has_access,
        'message' => $has_access ? '有权限访问此功能' : '无权限访问此功能'
    ];
}

/**
 * 获取许可证详情
 */
function spider_get_license_details($license_key, $domain = '') {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    
    // 验证许可证密钥格式
    if (!spider_validate_license_key($license_key)) {
        return new WP_Error('invalid_key', '许可证密钥格式无效');
    }
    
    // 查找许可证
    $license = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$licenses_table} WHERE license_key = %s",
        $license_key
    ));
    
    if (!$license) {
        return [
            'success' => false,
            'message' => '许可证不存在或无效'
        ];
    }
    
    // 获取激活信息
    $activations = [];
    if (!empty($domain)) {
        $activated = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$activations_table} WHERE license_id = %d AND domain = %s",
            $license->id,
            $domain
        )) > 0;
    } else {
        $activated = false;
    }
    
    // 获取所有激活的域名
    $activated_domains = $wpdb->get_col($wpdb->prepare(
        "SELECT domain FROM {$activations_table} WHERE license_id = %d",
        $license->id
    ));
    
    return [
        'success' => true,
        'license_key' => $license_key,
        'plan' => $license->plan,
        'expires_at' => $license->expires_at,
        'features' => json_decode($license->features, true),
        'max_domains' => (int) $license->max_domains,
        'current_activations' => count($activated_domains),
        'activated_domains' => $activated_domains,
        'is_activated' => $activated,
        'is_expired' => strtotime($license->expires_at) < current_time('timestamp'),
        'created_at' => $license->created_at
    ];
}

/**
 * 获取许可证激活记录
 */
function spider_get_license_activations($license_id) {
    global $wpdb;
    
    return $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}spider_license_activations WHERE license_id = %d ORDER BY activated_at DESC",
            $license_id
        ),
        ARRAY_A
    );
}

/**
 * 获取统计信息
 */
function spider_get_license_stats() {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    $activations_table = $wpdb->prefix . 'spider_license_activations';
    
    $total_licenses = $wpdb->get_var("SELECT COUNT(*) FROM {$licenses_table}");
    $active_licenses = $wpdb->get_var("SELECT COUNT(*) FROM {$licenses_table} WHERE expires_at > NOW()");
    $total_activations = $wpdb->get_var("SELECT COUNT(*) FROM {$activations_table}");
    
    return [
        'total_licenses' => (int) $total_licenses,
        'active_licenses' => (int) $active_licenses,
        'total_activations' => (int) $total_activations
    ];
}

/**
 * 导出许可证
 */
function spider_export_licenses() {
    global $wpdb;
    
    $licenses_table = $wpdb->prefix . 'spider_licenses';
    
    $licenses = $wpdb->get_results(
        "SELECT license_key, expires_at, max_domains, created_at FROM {$licenses_table} ORDER BY created_at DESC"
    );
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="spider-licenses-' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, ['许可证密钥', '到期时间', '最大域名数', '创建时间']);
    
    foreach ($licenses as $license) {
        fputcsv($output, [
            $license->license_key,
            $license->expires_at,
            $license->max_domains,
            $license->created_at
        ]);
    }
    
    fclose($output);
    exit;
}

/**
 * 服务器端订阅客户端类
 */
if (!class_exists('Spider_Server_Subscription_Client')) {
class Spider_Server_Subscription_Client {
    private $service;
    
    public function __construct() {
        $this->service = new Spider_License_Service();
    }
    
    public function is_activated() {
        // 检查是否有激活的许可证
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            return false;
        }
        
        $domain = home_url();
        $result = $this->service->verify_license($license_key, $domain);
        return $result['success'] && ($result['status'] ?? '') === 'active';
    }
    
    public function activate_license($license_key) {
        $domain = home_url();
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        $result = $this->service->activate_license($license_key, $domain, $ip_address, $user_agent);
        
        if ($result['success']) {
            update_option('spider_license_key', $license_key);
        }
        
        return $result;
    }
    
    public function deactivate_license() {
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            return ['success' => false, 'message' => '没有激活的许可证'];
        }
        
        $domain = home_url();
        $result = $this->service->deactivate_license($license_key, $domain);
        
        if ($result['success']) {
            delete_option('spider_license_key');
        }
        
        return $result;
    }
    
    public function get_license_info() {
        $license_key = get_option('spider_license_key', '');
        if (empty($license_key)) {
            return null;
        }
        
        $domain = home_url();
        return $this->service->get_license_details($license_key, $domain);
    }
}

// 初始化全局客户端实例
if (!isset($GLOBALS['spider_subscription_client'])) {
    $GLOBALS['spider_subscription_client'] = new Spider_Server_Subscription_Client();
}

/**
 * 许可证服务类
 */
class Spider_License_Service {
    private $api_base_url = 'https://zibovip.top/wp-json/spider-license/v1';
    
    public function verify_license($license_key, $domain) {
        global $wpdb;
        
        $licenses_table = $wpdb->prefix . 'spider_licenses';
        $activations_table = $wpdb->prefix . 'spider_license_activations';
        
        // 验证许可证
        $license = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$licenses_table} WHERE license_key = %s",
            $license_key
        ));
        
        if (!$license) {
            return ['success' => false, 'message' => '许可证密钥无效'];
        }
        
        // 检查是否过期（100年授权基本不会过期）
        if (strtotime($license->expires_at) < current_time('timestamp')) {
            return ['success' => false, 'message' => '许可证已过期'];
        }
        
        // 检查激活数量
        $activation_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$activations_table} WHERE license_key = %s",
            $license_key
        ));
        
        // 放宽限制：同一激活码在同一域名可重复使用，不计入额外占用；
        // 仅当尝试在新的域名激活且达到上限时才拦截
        $already_on_domain = (int)$wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$activations_table} WHERE license_key = %s AND domain = %s",
            $license_key, $domain
        ));
        if ($activation_count >= $license->max_domains && $already_on_domain == 0) {
            return ['success' => false, 'message' => '已达到最大激活域名数'];
        }
        
        // 返回许可证信息
        $features = json_decode($license->features, true);
        
        return [
            'success' => true,
            'license_key' => $license->license_key,
            'expires_at' => $license->expires_at,
            'features' => $features,
            'max_domains' => (int) $license->max_domains,
            'activation_count' => (int) $activation_count
        ];
    }
    
    public function get_license_details($license_key, $domain) {
        return $this->verify_license($license_key, $domain);
    }
    
    public function activate_license($license_key, $domain, $ip_address = '', $user_agent = '') {
        return spider_activate_license($license_key, $domain, $ip_address, $user_agent);
    }
    
    public function deactivate_license($license_key, $domain) {
        return spider_deactivate_license($license_key, $domain);
    }
    
    public function check_feature_access($license_key, $domain, $feature) {
        return spider_check_feature_access($license_key, $domain, $feature);
    }
}
}
?>